package function;

import Mysql.ShareData;
import View.FillInformationWindow;
import View.LoginWindow;
import View.MainWindow;
import View.window;
import client.ClientManager;
import client.Receive;
import client.Send;
import instruction.Login;
import instruction.Message;
import instruction.User;
import instruction.UserData;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.SQLException;

public class LoginFunction {
    public static Object $(window window, String id) {
        return (Object) window.getRoot().lookup("#" + id);
    }

    public static void loginExec(LoginWindow loginWindow, MainWindow mainWindow,ClientManager clientManager) {
        loginWindow.setFlag(false);
        ((Button) $(loginWindow, "loginButton")).setOnAction(actionEvent -> {
            loginWindow.resetErrorTip();//重置提示Label
            String account = ((TextField) $(loginWindow, "actText")).getText();
            String password = ((PasswordField) $(loginWindow, "pswText")).getText();
            if (account.equals("") || password.equals("")) {
                if (account.equals("")) {
                    loginWindow.setErrorTip("actTip", "账号不能为空!");
                }
                if (password.equals("")) {
                    loginWindow.setErrorTip("pswTip", "密码不能为空!");
                }
            } else {
                Message message=new Message("login");
                message.setLogin(new Login(account,password));
                    clientManager.getSend().send(message);
                    UserData userData=ShareData.UserDataMap.get(account);
                    if (userData!=null) {
                        mainWindow.setUserData(userData);
                        mainWindow.setClientManager(clientManager);
                        mainWindow.InitialUserData();//设置用户个人信息数据
                        mainWindow.InitialFriendList();//初始化好友列表
                        mainWindow.InitialGroupList();//初始化群聊列表
                        mainWindow.InitialMessageList();//初始化消息列表
                        mainWindow.InitialAssembly();//设置组件
                        try {
                            mainWindow.loadData();//载入数据
                        } catch (SQLException | IOException e) {
                            e.printStackTrace();
                        }
                        loginWindow.hide();
                        mainWindow.show();
                    } else {
                        loginWindow.setErrorTip("actTip", "登录中");
                    }

            }
        });
    }

}
